package com.ykdl.member.kid.gears;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.beans.GroupsBean;
import com.ykdl.member.kid.beans.IndexBean;
import com.ykdl.member.kid.beans.Invitation_StoresBean;
import com.ykdl.member.kid.beans.Listinfobean;
import com.ykdl.member.kid.beans.Memberlistbean;
import com.ykdl.member.kid.beans.ResultBean;
import com.ykdl.member.kid.beans.StoreInfoJsonBean;
import com.ykdl.member.kid.beans.SystemMessageExtraContextBean;
import com.ykdl.member.kid.beans.SystemMessageListBean;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

import android.widget.CheckedTextView;

public class BindStoreActivity extends BaseScreen implements OnClickListener {
	private CheckBox ischeck;
	private RefreshListView store_list;
	private BindStoreAdapter adapter;
	private Button cancle, determine;
	private ArrayList<StoreInfoJsonBean> store_info_list = new ArrayList<StoreInfoJsonBean>();
	private Invitation_StoresBean bean;
	private boolean isMulChoice = false;
	private ImageView select_all;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bindstore_list);

		WindowManager m = getWindowManager();
		Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高
		LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
		p.height = (int) (d.getHeight() * 0.8); // 高度设置为屏幕的0.8
		p.width = (int) (d.getWidth() * 0.87); // 宽度设置为屏幕的0.87
		p.alpha = 1.0f; // 设置本身透明度
		p.dimAmount = 0.6f; // 设置黑暗度
		getWindow().setAttributes(p);
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		store_list = (RefreshListView) findViewById(R.id.store_list);
		store_list.setMoreButtoIsGon(true);
		store_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub

				StoreInfoJsonBean bean = (StoreInfoJsonBean) adapter
						.getItem(arg2);
				if (adapter.checkedMap.get(arg2 - 1)) {
					adapter.getChecked_message_id().remove(bean.getStore_id());
					adapter.checkedMap.put(arg2 - 1, false);
				} else {
					if (!adapter.getChecked_message_id().contains(
							bean.getStore_id())) {
						adapter.getChecked_message_id().add(bean.getStore_id());
					}
					adapter.checkedMap.put(arg2 - 1, true);
				}

				String bindStoreIdString = adapter.getChecked_message_id()
						.toString().replace("[", "").replace("]", "");
				Log.e("alan", "---1---bindStoreIdString:" + bindStoreIdString);
				adapter.notifyDataSetChanged();
				if (adapter.getChecked_message_id().size() == adapter
						.getCount()) {
					select_all
							.setBackgroundResource(R.drawable.bind_check_true);
				} else {
					select_all
							.setBackgroundResource(R.drawable.bind_check_false);
				}
			}
		});
		adapter = new BindStoreAdapter();
		select_all = (ImageView) findViewById(R.id.select_all);
		select_all.setOnClickListener(this);
		cancle = (Button) findViewById(R.id.cancle);
		cancle.setOnClickListener(this);
		determine = (Button) findViewById(R.id.determine);
		determine.setOnClickListener(this);

		bean = (Invitation_StoresBean) this.getIntent().getSerializableExtra(
				"Invitation_store");
		if (bean != null && bean.getStore_list().size() > 0) {
			store_info_list = bean.getStore_list();
			adapter.setList(store_info_list);
			adapter.notifyDataSetChanged();
			store_list.setAdapter(adapter);
		} else {
			Toast.makeText(mContext, "没有数据", 0).show();
		}
		store_list.setAdapter(adapter);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.cancle:
			finish();

			break;
		case R.id.determine:
			String bindStoreIdString = adapter.getChecked_message_id()
					.toString().replace("[", "").replace("]", "");
			Log.e("alan", "------bindStoreIdString:" + bindStoreIdString);
			if (bean.getCan_join_stores_num() < adapter.getChecked_message_id()
					.size()) {
				Toast.makeText(mContext, "最多只能绑定五个门店哦！", 0).show();
				return;
			}
			if (!bindStoreIdString.equals("")) {
				 bindStore(bindStoreIdString);
			} else {
				Toast.makeText(mContext, "请选择门店", 1).show();
			}
			break;
		case R.id.select_all:
			int index = adapter.getCount();
			if (!isMulChoice) {
				select_all.setBackgroundResource(R.drawable.bind_check_true);
				adapter.getChecked_message_id().clear();
				for (int i = 0; i < index; i++) {
					adapter.checkedMap.put(i, true);
					adapter.checked_message_id.add(bean.getStore_list().get(i).getStore_id());
					adapter.notifyDataSetChanged();
					isMulChoice = true;
				}
			} else {
				select_all.setBackgroundResource(R.drawable.bind_check_false);
				for (int i = 0; i < index; i++) {
					adapter.checkedMap.put(i, false);
					adapter.notifyDataSetChanged();
					isMulChoice = false;
				}
				adapter.getChecked_message_id().clear();
			}
			break;
		default:
			break;
		}
	}

	private void bindStore(String store_ids) {
		// TODO Auto-generated method stub
		showProgress("正在加载中,请稍等...");
		String pageurl = KidConfig.JIHUO_LIBAO;
		HttpParameters parameterss = new HttpParameters();
		parameterss.put("store_ids", store_ids.toString());
		HttpBaseRequest request = Wxxr.getInstance().postBaseRequest(pageurl,
				parameterss, null);
		TaskManager.startHttpRequest(request, new getDataTag(),
				ResultBean.class);
	}

	class getDataTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof ResultBean) {
				final ResultBean bean = (ResultBean) t;
				if (bean.getError() == null) {
					Toast.makeText(mContext, bean.getMessage(), 0).show();
					setResult(200);
					finish();
				} else {
					Toast.makeText(mContext, bean.getDesc(), 0).show();
				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "失败", 0).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			finishProgress();
		}

	}

	class BindStoreAdapter extends BaseAdapter {
		private ArrayList<StoreInfoJsonBean> list;
		public Map<Integer, Boolean> checkedMap; // 保存checkbox是否被选中的状态
		private ArrayList<String> checked_message_id; // 该集合存储被选中的列表项中message_id

		public ArrayList<String> getChecked_message_id() {
			return checked_message_id;
		}

		public BindStoreAdapter() {
			checkedMap = new HashMap<Integer, Boolean>();
			checked_message_id = new ArrayList<String>();

		}

		public void setList(ArrayList<StoreInfoJsonBean> list) {
			this.list = list;
			for (int i = 0; i < list.size(); i++) {
				checkedMap.put(i, false);
			}
		}

		@Override
		public int getCount() {
			if (list != null) {
				return list.size();
			} else {
				return 0;
			}
		}

		@Override
		public Object getItem(int arg0) {
			if (getCount() != 0) {
				return list.get(arg0 - 1);
			} else {
				return null;
			}
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			final int index = position;
			if (convertView == null) {
				convertView = RelativeLayout.inflate(mContext,
						R.layout.bindstore_item, null);
				holder = new ViewHolder();
				holder.ischeck = (ImageView) convertView
						.findViewById(R.id.ischeck);
				holder.store_name = (TextView) convertView
						.findViewById(R.id.store_name);
				holder.address = (TextView) convertView
						.findViewById(R.id.address);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (checkedMap.get(position)) {
				holder.ischeck
						.setBackgroundResource(R.drawable.bind_check_true);
			} else {
				holder.ischeck
						.setBackgroundResource(R.drawable.bind_check_false);
			}
//			 holder.ischeck.setChecked(checkedMap.get(position));
			if (checkedMap.get(position)) {
				if (!checked_message_id.contains(list.get(index).getStore_id()
						+ "")) {
					checked_message_id.add(list.get(index).getStore_id() + "");
				}
			} else {
				checked_message_id.remove(list.get(index).getStore_id() + "");
			}
			holder.store_name.setText(list.get(position).getName());
			holder.address.setText("地址： "
					+ list.get(position).getStore_address());
			/*
			 * holder.ischeck .setOnCheckedChangeListener(new
			 * OnCheckedChangeListener() {
			 * 
			 * @Override public void onCheckedChanged(CompoundButton buttonView,
			 * boolean isChecked) { // TODO Auto-generated method stub if
			 * (isChecked) { if (!checked_message_id.contains(list
			 * .get(index).getStore_id() + "")) {
			 * checked_message_id.add(list.get(index) .getStore_id() + "");
			 * checkedMap.put(index, true); }
			 * 
			 * } else { checkedMap.put(index, false);
			 * checked_message_id.remove(list.get(index) .getStore_id() + ""); }
			 * String bindStoreIdString = getChecked_message_id()
			 * .toString().replace("[", "") .replace("]", ""); Log.e("alan",
			 * "--2----bindStoreIdString:" + bindStoreIdString); if
			 * (adapter.getChecked_message_id().size() == adapter .getCount()) {
			 * select_all.setBackgroundResource(R.drawable.bind_check_true);
			 * Log.e("alan", "--2----全选按钮:" + "选中"); } else {
			 * select_all.setBackgroundResource(R.drawable.bind_check_false);
			 * Log.e("alan", "--2----全选按钮:" + "未选中"); } } });
			 */
			return convertView;
		}

		class ViewHolder {
			ImageView ischeck;
			TextView store_name;
			TextView address;
		}

	}

}
